<template>
  <refresh-list
    ref="refreshList"
    :enable-pull-refresh="false"
    @pull-load="onListLoad"
  >
    <comment-item
      class="commenter"
      :comment="comment"
      :reply-show="false"
    />
    <p class="count">相关回复共 {{comment.rcount}} 条</p>
    <comment-item
      v-for="item in replies"
      :key="item.rpid"
      :comment="item"
      :reply-show="false"
    />
  </refresh-list>
</template>

<script>
import { apiGetMoreReply } from '@/api/comment'
import CommentItem from './CommentItem'
import RefreshList from '@/components/refresh-list/RefreshList'
export default {
  name: 'CommentReply',
  components: {
    RefreshList,
    CommentItem
  },
  props: {
    // 评论数据
    comment: {
      type: Object
    }
  },
  data () {
    return {
      pageIndex: null,
      replies: []
    }
  },
  computed: {
    // oid 评论所属id
    oid () {
      return this.comment.oid
    },
    // rpid 原评论的 id
    root () {
      return this.comment.rpid
    },
    // type 评论所属类型 1是视频评论 28是投票评论
    type () {
      return this.comment.type
    }
  },
  watch: {
    comment: {
      deep: true,
      handler (newVal) {
        this.reset()
        this.getData()
      }
    }
  },
  created () {
    this.getData()
  },
  methods: {
    reset () {
      this.$refs.refreshList && this.$refs.refreshList.reset()
      this.replies = []
    },
    onListLoad () {
      clearTimeout(this.listTimeout)
      if (!this.$refs.refreshList.isFinished()) {
        this.listTimeout = setTimeout(() => {
          this.getData()
        }, 1000)
      }
    },
    getData () {
      apiGetMoreReply({
        oid: this.oid,
        type: this.type,
        root: this.root,
        pageIndex: this.pageIndex
      }).then(res => {
        const { code, data } = res
        if (code === 0 && data) {
          const { root: { replies }, cursor } = data
          const minId = cursor.min_id
          const allCount = cursor.all_count
          const maxId = cursor.max_id
          for (const reply of replies) {
            const { rpid } = reply
            const matchIndex = this.replies.findIndex(re => re.rpid === rpid)
            if (matchIndex < 0) {
              this.replies.push(reply)
            }
          }
          this.pageIndex = maxId
          if (minId >= allCount) {
            this.$refs.refreshList.completeLoad()
          }
        } else {
          this.$refs.refreshList.completeLoad()
        }
      }).catch(err => {
        console.log(err)
        this.$refs.refreshList.showError()
      }).finally(() => {
        this.$refs.refreshList.stopLoad()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .commenter{
    margin-top: 0;
  }
  .count{
    font-size: 12px;
    color: $color-text-secondary;
    margin: 0;
    height: 30px;
    line-height: 30px;
  }
</style>
